<template>
  <div>
    <a-descriptions :align="{ label: 'right' }">
      <a-descriptions-item label="车辆费用单号">{{ feeDetail?.businesCode || '-' }}</a-descriptions-item>
      <a-descriptions-item label="车辆费用金额">{{ feeDetail?.otherFeeTotalAmount }} 元</a-descriptions-item>
      <a-descriptions-item label="车辆实付金额">{{ feeDetail?.otherFeeHarvestAmount }} 元</a-descriptions-item>
      <a-descriptions-item label="车辆待付金额">{{ feeDetail?.otherFeePayableAmount }} 元</a-descriptions-item>
      <a-descriptions-item label="车辆实收金额">{{ feeDetail?.otherFeeNetReceiptsAmount }} 元</a-descriptions-item>
      <a-descriptions-item label="车辆待收金额">{{ feeDetail?.otherFeePayableAmountHarvest }} 元</a-descriptions-item>
    </a-descriptions>
  </div>
  <a-alert title="请注意：" style="margin-top: 24px; margin-bottom: 24px"> 【借调费】需按分期顺序确认账单，不支持跳期确认账单 </a-alert>
  <table-index
    class="insure-card-table"
    :table="tableCompulsory"
    :selectedKeys="selectedRowKeys"
    @selection-change="selectionChange"
    @loadData="loadData"
  >
    <template #feeCategoryName="{ record }">
      <div v-if="record.installment == 0">{{ record.feeName }}</div>
      <div v-else>{{ record.feeCategoryName }} - {{ record.feeName }}</div>
    </template>
    <template #dueDate="{ record }">
      <div> {{ record.dueDate ? dayjs(record.dueDate).format('YYYY-MM-DD') : '-' }}</div>
    </template>
  </table-index>
  <!-- </a-table> -->
  <ConfirmCost ref="confirm_cost" @confirm="handleConfirmToFetch" />
  <modifyCost ref="modifyCostRef" @confirm="refreshData" />
</template>
<script setup>
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useTable } from '@/hooks/table'
  import { getFeeInfoList, checkBatchConfirm } from '@/api/asset/carTransfer'
  import dayjs from 'dayjs'
  import { Message } from '@arco-design/web-vue'
  import ConfirmCost from '../../../../../assets/operation/car-transfer/compoents/confirm-cost.vue'
  import EditFee from '../../../../../assets/operation/car-transfer/compoents/editFee.vue'
  import EditFeeNoByStages from '../../../../../assets/operation/car-transfer/compoents/noByStages.vue'
  import modifyCost from '../../../../../assets/car/car-manage/modify-cost.vue'
  const props = defineProps({
    carId: {
      type: [Number, String],
    },
    type: {
      type: [Number, String],
    },
    code: {
      type: [Number, String],
    },
  })

  const pagination = { pageSize: 1000 }

  const selectedKeys = ref([])

  const feeDetail = ref({})

  const queryParam = reactive({
    feeCategoryList: [6],
    carId: props.carId,
    businesCode: props.code,
  })

  const tableCompulsory = useTable({
    pagination: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      { title: '费用名称', dataIndex: 'feeCategoryName', width: 160, slotName: 'feeCategoryName' },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 120 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 120 },
      {
        title: '应结日期',
        dataIndex: 'dueDate',
        slotName: 'dueDate',
        width: 140,
      },
      { title: '费用金额(元)', dataIndex: 'totalAmount', width: 140 },
      { title: '实结金额(元)', dataIndex: 'payAmount', width: 140 },
      { title: '待结金额(元)', dataIndex: 'outstandingAmount', width: 140 },
      { title: '生成节点', dataIndex: 'createNodeName', width: 120 },
      { title: '生成时间', dataIndex: 'createTime', width: 180 },
      { title: '收支方式', dataIndex: 'payTypeName', width: 120 },
      { title: '费用状态', dataIndex: 'feeStatusName', width: 120 },
      { title: '确认时间', dataIndex: 'confirmTime', width: 180 },
      { title: '确认人', dataIndex: 'confirmUserName', width: 120 },
      { title: '费用备注', dataIndex: 'remark', ellipsis: true, width: 140 },
      { title: '结算备注', dataIndex: 'settlementRemark', ellipsis: true, width: 140 },
    ],
    buttons: [
      {
        type: 'primary',
        label: '批量结算',
        method: () => {
          if (selectedRowKeys.value.length == 0) {
            Message.error('请勾选您要批量结算的费用')
            return
          }
          toCheck()
        },
      },
    ],
    operates: [
      {
        label: '结算',
        show: (record, column, rowIndex) => record.feeStatus == 0 || record.feeStatus == 3 || record.feeStatus == 5,
        method: (record, column, rowIndex) => {
          handleConfirm(record, rowIndex)
        },
      },
      {
        label: '修改费用',
        show: (record, column, rowIndex) => record.feeStatus == 0 || record.feeStatus == 3 || record.feeStatus == 5,
        method: (record, column, rowIndex) => {
          handleEditFee(record)
        },
      },
    ],
    dataList: [],
  })
  // 列表接口调用
  const loadData = () => {
    tableCompulsory.tableLoading = true
    getFeeInfoList({ ...queryParam }).then((res) => {
      if (res.code == 200) {
        tableCompulsory.tableLoading = false
        feeDetail.value = res.result
        tableCompulsory.dataList = res.result.carAssetFeeList || []
        tableCompulsory.dataList.forEach((item) => {
          if (item.feeStatus == 0 || item.feeStatus == 3 || item.feeStatus == 5) {
            item.disabled = false
          } else {
            item.disabled = true
          }
        })
        console.log(tableCompulsory.dataList)
      }
    })
  }
  const selectedRowKeys = ref([])
  // 业务单ID
  const businesId = ref('')
  // 期数ID
  const installmentIds = []
  const selectionChange = (e) => {
    selectedRowKeys.value = e
    renderSelectId()
  }
  const renderSelectId = () => {
    // 清空之前的值
    businesId.value = '' // 重新赋值空字符串
    installmentIds.value = [] // 清空 installmentIds 数组

    // 遍历 dataList，检查 id 是否在 selectedRowKeys.value 中
    tableCompulsory.dataList.forEach((record) => {
      const index = selectedRowKeys.value.indexOf(record.id)
      if (index !== -1) {
        // 如果 id 匹配，且 businesId.value 为空，就赋值 businesId.value 为第一个匹配项的 businesId
        if (businesId.value === '') {
          businesId.value = record.businesId // 只取第一个匹配的 businesId
        }
        // 添加 payableNum 到 installmentIds.value
        installmentIds.value.push(record.payableNum)
      }
    })
  }
  const modifyCostRef = ref(null)
  const handleEditFee = (record) => {
    if (record.feeNameId == 61 || record.feeNameId == 58) {
      modifyCostRef.value.open({
        id: record.id,
        feeNameId: record.feeNameId,
        feeCategory: record.feeCategory,
        installment: record.installment,
        businesId: feeDetail.value.businesId,
        businesCode: feeDetail.value.businesCode,
        carId: record.carId,
        feeNameId: record.feeNameId,
        title: `修改费用-${feeDetail.value.carLicenseNo}`,
      })
    } else {
      modifyCostRef.value.open({
        id: record.businesId,
        feeNameId: record.feeNameId,
        feeCategory: record.feeCategory,
        installment: record.installment,
        businesId: feeDetail.value.businesId,
        businesCode: feeDetail.value.businesCode,
        carId: record.carId,
        feeNameId: record.feeNameId,
        title: `修改费用-${feeDetail.value.carLicenseNo}`,
      })
    }
  }

  const confirm_cost = ref(null)
  const handleConfirm = (record, index) => {
    if (index != 0) {
      // 1:已付款 2:已收款
      if (tableCompulsory.dataList[index - 1].feeStatus == 1 || tableCompulsory.dataList[index - 1].feeStatus == 2) {
        confirm_cost.value.open(record.id, props.type)
      } else if (record.installment == 0) {
        confirm_cost.value.open(record.id, props.type)
      } else {
        Message.error('请按顺序结算')
      }
    } else {
      confirm_cost.value.open(record.id, props.type)
    }
  }

  const toCheck = () => {
    let selectedRows = []
    tableCompulsory.dataList.forEach((item) => {
      selectedRowKeys.value.forEach((ele) => {
        if (item.id == ele) {
          selectedRows.push(item)
        }
      })
    })
    let flag = selectedRows.every((item) => {
      return item.feeStatus == 0 || item.feeStatus == 3 || item.feeStatus == 5
    })
    if (!flag) {
      Message.error('费用状态为[ 已付款、已收款、已作废 ]不支持确认费用')
      return
    }
    let installmentList = []
    selectedRows.forEach((des) => {
      installmentList.push(des.payableNum)
    })
    let params = {
      businesId: selectedRows[0].businesId,
      installmentList: installmentList,
      idList: selectedRowKeys.value,
    }
    checkBatchConfirm(params).then((res) => {
      if (res.code == 200 && res.result) {
        confirm_cost.value.open(selectedRowKeys.value, props.type)
      }
    })
  }

  const handleConfirmToFetch = () => {
    loadData()
    selectedRowKeys.value = []
  }

  const refreshData = () => {
    loadData()
  }

  onMounted(() => {
    loadData()
  })
</script>

<style lang="less" scoped>
  .second-stage {
    width: 200px;
    margin-left: 260px;
  }
  .third-stage {
    width: 200px;
    margin-left: 30px;
  }
  .btn-box {
    display: flex;
    justify-content: space-between;
    padding: 18px;
    align-items: center;
  }
  .blue-text {
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #3370ff;
    cursor: pointer;
  }
</style>
